# -*- coding: utf-8 -*-
# Create your views here.
from buscador.forms import DocumentoBuscarForm
from django.contrib.auth.decorators import login_required, permission_required, \
    user_passes_test, login_required, permission_required, user_passes_test
from django.core.context_processors import csrf
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response, get_object_or_404
from django.template.context import RequestContext
from django.views.generic.create_update import update_object, create_object, \
    delete_object
from django.views.generic.list_detail import object_list, object_detail
from documentos.forms import DocumentoForm
from documentos.models import Documento
from usuarios.permisos import es_del_grupo_de_expertos


def listar(request):    #seria la pagina de inicio para las proyectos
    return object_list(request,
                       queryset = Documento.objects.all(),
                       allow_empty = True,
                       template_name = 'documentos/listar.html'
                       )
    
def filtrar(request):    #seria la pagina de inicio para las especies
    form = DocumentoBuscarForm()
    q = None
    if request.method == 'POST':
        form = DocumentoBuscarForm(request.POST)
        if form.is_valid():
            q = Documento.objects
            if form.cleaned_data['nombre']:
                q =  q.filter(nombre__icontains = form.cleaned_data['nombre'])
            if form.cleaned_data['tipo']:
                q = q.filter(tipo = form.cleaned_data['tipo'])
            if form.cleaned_data['campo']:
                q =  q.filter(datos = form.cleaned_data['campo'])
            if form.cleaned_data['pais']:
                q =  q.filter(pais = form.cleaned_data['pais'])
            if form.cleaned_data['institucion']:
                q =  q.filter(institucion = form.cleaned_data['institucion'])
            if form.cleaned_data['linea']:
                q =  q.filter(lineas = form.cleaned_data['linea'])
            if form.cleaned_data['proyecto']:
                q =  q.filter(documentos_relacionados = form.cleaned_data['proyecto'])
            if form.cleaned_data['creador']:
                q =  q.filter(creador = form.cleaned_data['creador'])
            if q == Documento.objects:
                q = None
    return object_list(request,
                       queryset = Documento.objects.all(),
                       allow_empty = True,
                       extra_context = {'form' : form, 'detalles' : q },
                       template_name = 'documentos/filtrar.html'
                       )


def ver(request, object_id):
    documento = get_object_or_404(Documento, pk=object_id)
    extra_context = {'object_id':documento.pk} 
    puede_ver = True
    if documento.nivel == 'US' and not request.user.is_authenticated():
        puede_ver = False
    try:
        if documento.nivel == 'EX' and not request.user.get_profile().experto:
            puede_ver = False
    except:
        puede_ver = False
    if documento.nivel == 'AD' and not request.user.is_superuser:
        puede_ver = False
    
    if not puede_ver:
        extra_context.update({'error':u'El nivel de acceso no le permite acceder a este documento'})
        extra_context.update({'titulo_error':u'No se puede ver el documento'})
        return render_to_response("documentos/error.html", extra_context,context_instance=RequestContext(request))
    
    
    return object_detail(request,
                         queryset = Documento.objects.all(),
                         template_object_name =  "Documento",
                         template_name = 'documentos/detalle.html',
                         object_id = object_id
                         )
    

@login_required
@user_passes_test(es_del_grupo_de_expertos,login_url='/accounts/signin/no_experto')
def crear(request):
    return create_object(request,
                         model = Documento,
                         form_class = DocumentoForm,
                         template_name = 'documentos/crear.html',
                         #post_save_redirect = '/documentos/'
                         )    

@login_required
@user_passes_test(es_del_grupo_de_expertos,login_url='/accounts/signin/no_experto')
def crear_con_experto(request):
    c={}
    if request.method == 'POST':                            
        form = DocumentoForm(request.POST,request.FILES)                                                
        if form.is_valid():                                  
            new_doc = form.save(commit=False)
            try:
                new_doc.creador = request.user.get_profile().experto
                new_doc.save()
                form.save_m2m()
            except:
                c.update({'error':u'No tiene perfil de Experto. El Documento no se guardó.'})
                c.update(csrf(request))
                c.update({'form':form}) 
                return render_to_response("documentos/crear.html", c,context_instance=RequestContext(request))
                       
            return HttpResponseRedirect('/documentos/' + str(new_doc.pk))
    else:
        form = DocumentoForm()
        
    c.update(csrf(request))
    c.update({'form':form})                 
    return render_to_response("documentos/crear.html", c,context_instance=RequestContext(request))



@login_required
@user_passes_test(es_del_grupo_de_expertos,login_url='/accounts/signin/no_admin')
def editar(request, object_id):
    c = {}
    documento = get_object_or_404(Documento, pk=object_id)
    try:
        if request.user.get_profile().experto == documento.creador:
            return update_object(request,
                         model = Documento,
                         form_class = DocumentoForm,
                         template_name = 'documentos/editar.html',
                         post_save_redirect = '/documentos/' + object_id,
                         object_id = object_id
                         )
        else:
            c.update({'error':u'Usted tiene perfil de Experto pero no es el creador'})  
            
    except:   
        c.update({'error':u'Usted no tiene perfil de Experto, no puede editar el documento'})
    c.update({'titulo_error':u'No se pudo modificar el documento'})
    c.update({'object_id':object_id})               
    c.update(csrf(request))
    return render_to_response("documentos/error.html", c,context_instance=RequestContext(request))
    


@login_required
@user_passes_test(es_del_grupo_de_expertos,login_url='/accounts/signin/no_experto')
def eliminar(request, object_id):
    c = {}
    documento = get_object_or_404(Documento, pk=object_id)
    try:
        if request.user.get_profile().experto == documento.creador:
            return delete_object(request,
                         model = Documento,
                         template_name = 'documentos/confirmar_eliminar.html',
                         post_delete_redirect = '/documentos/',
                         object_id = object_id
                         )
        else:
            c.update({'error':u'Usted tiene perfil de Experto pero no es el creador'})  
            
    except:   
        c.update({'error':u'Usted no tiene perfil de Experto'})
    c.update({'titulo_error':u'No se pudo eliminar el documento'})
    c.update({'object_id':object_id})               
    c.update(csrf(request))
    return render_to_response("documentos/error.html", c,context_instance=RequestContext(request))

